/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package components.panels;

import entity.Address;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Juan
 */
public class PAddresses extends javax.swing.JPanel {

    /**
     * Creates new form PPhoneNumbers
     */
    public PAddresses() {
        initComponents();
        TAdresses.getTableHeader().setReorderingAllowed(false);
        TAdresses.getColumn("Dirección").setPreferredWidth(750);
        TAdresses.getColumn("Correspondencia").setPreferredWidth(100);
        TAdresses.getColumn("Devolución de Muestras").setPreferredWidth(130);
        TAdresses.getColumn("Envío de Resultados").setPreferredWidth(110);
        addTableSelectionListener();
    }
    
    private void addTableSelectionListener() {
        TAdresses.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

            @Override
            public void valueChanged(ListSelectionEvent e) {
                if (TAdresses.getSelectedRow() != -1) {
                    BRemove.setEnabled(true);
                    BSelectAll.setEnabled(true);
                }else{
                    BRemove.setEnabled(false);
                    BSelectAll.setEnabled(false);
                }
            }
        });
    }
    
    public ArrayList getAddresses() {
        ArrayList addresses = new ArrayList();
        DefaultTableModel model = (DefaultTableModel) TAdresses.getModel();
        
        for (int row = 0; row < model.getRowCount(); row++) {
            String address = (String) model.getValueAt(row, 0);
            if (address != null && address.length() != 0) {
                Address currentAddress = new Address();
                currentAddress.setAddress(address);
                StringBuilder stringBuilder = new StringBuilder();
                for (int col = 1; col < model.getColumnCount(); col++) {
                    if ((boolean) model.getValueAt(row, col))
                        stringBuilder.append("1");
                    else
                        stringBuilder.append("0");
                }
                currentAddress.setType(stringBuilder.toString());
                addresses.add(currentAddress);
            }
        }
        return addresses;
    }
    
    public void setAdresses(List addresses) {
        BAdd.setVisible(false);
        BRemove.setVisible(false);
        BSelectAll.setVisible(false);
        TAdresses.setEnabled(false);
        
        DefaultTableModel model = (DefaultTableModel) TAdresses.getModel();
        model.setRowCount(0);
        
        if (addresses != null) {
            for (Iterator it = addresses.iterator(); it.hasNext();) {
                Address address = (Address) it.next();
                String type = address.getType();
                model.addRow(new Object[]{address.getAddress(),
                            type.substring(0, 1).equals("1"),
                            type.substring(1, 2).equals("1"),
                            type.substring(2, 3).equals("1"),
                            type.substring(3, 4).equals("1")});
            }
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        LTitle = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TAdresses = new javax.swing.JTable();
        BAdd = new javax.swing.JButton();
        BRemove = new javax.swing.JButton();
        BSelectAll = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createEtchedBorder());

        LTitle.setText("Direcciones:");

        TAdresses.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"",  new Boolean(false),  new Boolean(false),  new Boolean(false),  new Boolean(false)}
            },
            new String [] {
                "Dirección", "Correspondencia", "Devolución de Muestras", "Facturación", "Envío de Resultados"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        TAdresses.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jScrollPane1.setViewportView(TAdresses);

        BAdd.setText("Agregar");
        BAdd.setToolTipText("Agregar un campo para Dirección");
        BAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAddActionPerformed(evt);
            }
        });

        BRemove.setText("Eliminar");
        BRemove.setToolTipText("Eliminar el campo seleccionado");
        BRemove.setEnabled(false);
        BRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BRemoveActionPerformed(evt);
            }
        });

        BSelectAll.setText("Seleccionar Casillas");
        BSelectAll.setToolTipText("Seleccionar o deseleccionar todas las casillas");
        BSelectAll.setEnabled(false);
        BSelectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BSelectAllActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(LTitle)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(BAdd)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BRemove)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(BSelectAll)))
                .addGap(0, 119, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(LTitle)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(BRemove)
                        .addComponent(BSelectAll))
                    .addComponent(BAdd)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAddActionPerformed
        DefaultTableModel model = (DefaultTableModel) TAdresses.getModel();
        model.addRow(new Object[] {"",false,false});
    }//GEN-LAST:event_BAddActionPerformed

    private void BRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BRemoveActionPerformed
        DefaultTableModel model = (DefaultTableModel) TAdresses.getModel();
        int selectedRow = TAdresses.getSelectedRow();
        model.removeRow(selectedRow);
        
        if (selectedRow == 0)
            if (TAdresses.getRowCount() == 0)
                TAdresses.getSelectionModel().setSelectionInterval(-1, -1);
            else
                TAdresses.getSelectionModel().setSelectionInterval(0, 0);
        else
            TAdresses.getSelectionModel().setSelectionInterval(selectedRow - 1, selectedRow - 1);
    }//GEN-LAST:event_BRemoveActionPerformed

    private void BSelectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BSelectAllActionPerformed
        int selectedRow = TAdresses.getSelectedRow();
        int selectedFields = 0;
        boolean newValue = true;
        
        //Check how many fields are selected
        for (int i = 1; i < TAdresses.getColumnCount(); i++) {
            if ((boolean) TAdresses.getValueAt(selectedRow, i))
                selectedFields++;
        }
        
        //If they are all selected, unselect them all. Otherwise select them all.
        if (selectedFields == TAdresses.getColumnCount() -1)
            newValue = false;
        
        for (int i = 1; i < TAdresses.getColumnCount(); i++) {
            TAdresses.setValueAt(newValue, selectedRow, i);
        }
    }//GEN-LAST:event_BSelectAllActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAdd;
    private javax.swing.JButton BRemove;
    private javax.swing.JButton BSelectAll;
    private javax.swing.JLabel LTitle;
    private javax.swing.JTable TAdresses;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
